import React, { useRef } from 'react'
import './index.less'
import { useState } from '../hooks/useHooks'

const RequestAnimationFrameDemo = () => {
	const demoRef = useRef()
	const [animationId, setAnimationId] = useState(-1)
	const [move, setMove] = useState(0)
	let start

	const step = (timestamp) => {
		if (!demoRef.current) return
		if (start === undefined) start = timestamp
		const elapsed = timestamp - start
		//这里使用`Math.min()`确保元素刚好停在200px的位置。
		const distance = Math.min(move > 0.1 * elapsed ? move : 0.1 * elapsed, 500)
		setMove(distance)
		demoRef.current.style.transform = `translateX(${distance}px)`
		if (elapsed < 5000) {
			// 在两秒后停止动画
			const res = window.requestAnimationFrame(step)
			setAnimationId(res)
		} else {
			setMove(0)
		}
	}

	const startFn = () => {
		const res = window.requestAnimationFrame(step)
		setAnimationId(res)
	}

	const cancelFn = () => {
		window.cancelAnimationFrame(animationId)
	}

	return (
		<div>
			<div ref={demoRef} className={'animationBox'}></div>
			<button onClick={startFn}>开始</button>
			<button onClick={cancelFn}>取消</button>
		</div>
	)
}

export default RequestAnimationFrameDemo
